﻿using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using ARS.Control.Attributes;
using ARS.Control.Custom.DataPaging.Attributes;
using System;
using ARS.PublicTool.DataHandle;

namespace ARS.Control.Custom.DataPaging.Widget
{
    public class HtmlHelper
    {
        /// <summary>
        /// 操作列权限
        /// </summary>
        //private static bool isHasOperatPerm;
        Regex regex_field = new Regex(@"{{FieldName-(.*?)}}");
        Regex regex_urlField = new Regex(@"{{UrlName-(.*?)}}");
        /// <summary>
        /// 获取主键的值
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        protected virtual string GetKeyValue(ref string keyValue)
        {
            //
            return Encrypt.EncryptString(keyValue);
        }

        /// <summary>
        /// 获取tr里面field({{FieldName-}})列表
        /// </summary>
        /// <param name="trHtml"></param>
        /// <returns></returns>
        protected virtual string[] GetTrFieldList(ref string trHtml)
        {
            List<string> fieldList = new List<string>();
            MatchCollection matchList_Tr = regex_field.Matches(trHtml);
            foreach (Match match in matchList_Tr)
            {
                fieldList.Add(match.Groups[1].Value);
            }
            return fieldList.ToArray();
        }
        /// <summary>
        /// 生成tr的全部html
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="trHtml"></param>
        /// <returns></returns>
        protected virtual string GetTrAllHtml(DataPagingDb model, DataTable dt)
        {
            string tBodyTrHtml = model.HtmlTable.TBodyTrHtml;
            string[] trFieldList = GetTrFieldList(ref tBodyTrHtml);
            System.Text.StringBuilder sb = new StringBuilder();
            foreach (DataRow dr in dt.Rows)
            {
                sb.Append(this.GetTrLineHtml(model,dr,trFieldList, tBodyTrHtml));
            }
            return sb.ToString();
        }
        /// <summary>
        /// 获取tr行的模板html，<tr id='{2}'>{0}{1}</tr>
        /// </summary>
        /// <returns></returns>
        protected virtual string GetTrTemplateHtml(DataPagingDb model,DataRow dr)
        {
            return "<tr id='tr-{2}'>{0}{1}</tr>";
        }

        /// <summary>
        /// 获取tr行的html
        /// </summary>
        /// <param name="model"></param>
        /// <param name="dr"></param>
        /// <param name="trFieldList"></param>
        /// <param name="tr"></param>
        /// <returns></returns>
        protected virtual string GetTrLineHtml(DataPagingDb model, DataRow dr, string[] trFieldList, string tr)
        {
            //获取KEY
            string key;
            if (model.DbSelect.KeyField.Contains("."))
            {
                key = model.DbSelect.KeyField.Substring(model.DbSelect.KeyField.IndexOf(".") + 1);
            }
            else
            {
                key = model.DbSelect.KeyField;
            }
            string keyValue = dr[key].ToString();
            keyValue = GetKeyValue(ref keyValue);

            Match matchUrl = regex_urlField.Match(tr);
            if (matchUrl.Success)
            {
                string urlName = regex_urlField.Match(tr).Groups[1].Value;
                tr = regex_urlField.Replace(tr, string.Format(this.GetUrlTemplateHtml(), keyValue, dr[urlName]));
            }

            for (int i = 0; i < trFieldList.Length; i++)
            {
                //tr = regex_field.Replace(tr, dr[trFieldList[i]].ToString(), 1);
                tr = regex_field.Replace(tr, this.GetTbodyTdHtml(model,dr,trFieldList,i), 1);
            }

            tr = string.Format(tr, keyValue);
            return string.Format(this.GetTrTemplateHtml(model,dr), tr, GetOperatBodyHtml(model, dr, ref keyValue), keyValue);
        }

        protected virtual string GetTbodyTdHtml(DataPagingDb model, DataRow dr, string[] trFieldList, int index)
        {
            return dr[trFieldList[index]].ToString();
        }

        /// <summary>
        /// 获取链接列的url;
        /// </summary>
        /// <returns></returns>
        protected virtual string GetUrlTemplateHtml()
        {
            
            return "<a href='#Id={0}'>{1}</a>";
        }


        public virtual string GetTreeLineHtml(string lineHtml, DataRow dr, DbSelectAll DbSelect)
        {
            string[] trFieldList = GetTrFieldList(ref lineHtml);
            string line = lineHtml;
            for (int i = 0; i < trFieldList.Length; i++)
            {
                line = regex_field.Replace(line, dr[trFieldList[i]].ToString(), 1);
            }
            string key;
            if (DbSelect.KeyField.Contains("."))
            {
                key = DbSelect.KeyField.Substring(DbSelect.KeyField.IndexOf(".") + 1);
            }
            else
            {
                key = DbSelect.KeyField;
            }
            string keyValue = dr[key].ToString();
            keyValue = GetKeyValue(ref keyValue);
            return string.Format(line, keyValue);
        }

        /// <summary>
        /// 获取操作列html
        /// </summary>
        /// <returns></returns>
        protected virtual string GetOperatBodyHtml(DataPagingDb model, DataRow dr, ref string keyValue)
        {
//            ARS.Control.Interface.IPermDataPaging perm = ARS.Control.Factory.PermDataPaging.CreatePermDataPaging();
            if (model.Operat.IsHasOperat)
            {
                if (model.Operat.OperatHtml == null)
                {
                    return null;
                }
                return string.Format(model.Operat.OperatHtml, keyValue);
            }
            return null;
        }

        /// <summary>
        /// 获取操作列标头
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        protected virtual string GetOperatHeadHtml(DataPagingDb model)
        {
            if (model.Operat.IsHasOperat)
            {
                return model.Operat.ColumnName;
            }
            return null;
        }

        //private static DataBase.Provider.IDataPagingProvider dataProvider = ARS.DataBase.Provider.DataPagingProvider.GetInstance();
        /// <summary>
        /// 获取全部html，包含div。以及更新ars_dataping数据库
        /// </summary>
        /// <param name="dbModel"></param>
        /// <returns></returns>
        public virtual string GetAllHtml(DataPagingDb dbModel)
        {
            //更新数据库存储
             ARS.DataBase.Provider.DbFactory.DpProvider.DataPagingDbAdd(dbModel);
            return string.Format("<div id='{1}Div'>{0}</div>",GetTableHtml(dbModel),dbModel.Status.ControlId);
        }
        public virtual string GetAllHtmlNoDiv(DataPagingDb dbModel)
        {
            //更新数据库存储
            ARS.DataBase.Provider.DbFactory.DpProvider.DataPagingDbAdd(dbModel);
            return GetTableHtml(dbModel);
        }

        private const string Str_Regex_Text = @"{{Text-(.*?)}}";
        static Regex regex_text = new Regex(Str_Regex_Text);
        /// <summary>
        /// 获取table模板html."<table class='{0}' id='datapagingtable'><thead><tr>{1}{3}</tr></thead><tbody id='datapagingbody'>{2}</tbody></table>{4}"
        /// </summary>
        /// <returns></returns>
        protected virtual string GetTableTemplateHtml(DataPagingDb dbModel)
        {
            return
                "<table class='{0}' id='datapagingtable'><thead><tr>{1}{3}</tr></thead><tbody id='datapagingbody'>{2}</tbody></table>{4}";
        }
        /// <summary>
        /// 将查询条件赋给参数
        /// </summary>
        /// <param name="dbModel"></param>
        public virtual void SetSearchWhere(DataPagingDb dbModel)
        {
            System.Action SetWhere = () =>
            {
                if (!string.IsNullOrEmpty(dbModel.DbSelect.UniteWhere))
                {
                    dbModel.DbSelect.StrWhere = dbModel.DbSelect.UniteWhere + " and " + dbModel.DbSelect.StrWhere;
                }
            };

            System.Action SetSearchWhere = () =>
            {
                string search = GetSearchValue(dbModel);
                if (!string.IsNullOrEmpty(search))
                {
                    //HttpContext.Current.res
                    string iswhere = HttpContext.Current.Request.Form["IsWithWhere"];
                    if (!string.IsNullOrEmpty(iswhere) && iswhere == "0")
                    {
                        dbModel.DbSelect.StrWhere = dbModel.DbSelect.UniteWhere + " and " + search;
                        return;
                    }
                    else
                    {
                        SetWhere();
                        dbModel.DbSelect.StrWhere = dbModel.DbSelect.StrWhere + " and " + search;
                        return;
                    }
                }
                SetWhere();
            };
            SetSearchWhere();
        }

        /// <summary>
        /// 只获取表格html.不更新数据库<table></table>
        /// </summary>
        /// <param name="dbModel"></param>
        /// <returns></returns>
        public virtual string GetTableHtml(DataPagingDb dbModel)
        {
            this.SetSearchWhere(dbModel);
            this._ds = this.GetDataSet(dbModel);
            return this.GetTableHtmlNoSearch(dbModel);
        }
        /// <summary>
        /// 只获取表格html.不更新数据库<table></table>
        /// </summary>
        /// <param name="dbModel"></param>
        /// <returns></returns>
        public virtual string GetTableHtmlNoSearch(DataPagingDb dbModel)
        {
            //DataSet ds = this.GetDataSet(dbModel);
            string trHtmlCode = this.GetTrAllHtml(dbModel, this._ds.Tables[0]);
            return string.Format(this.GetTableTemplateHtml(dbModel),
                dbModel.HtmlTable.TableCssName, dbModel.HtmlTable.THeadTrHtml, trHtmlCode, this.GetOperatHeadHtml(dbModel), GetFanyeHtmlIfHas(dbModel));
        }
        /// <summary>
        /// 查询出的数据
        /// </summary>
        protected DataSet _ds = null;
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="dbModel"></param>
        /// <returns></returns>
        public virtual DataSet GetDataSet(DataPagingDb dbModel)
        {
             DataSet ds = ARS.DataBase.Provider.DbFactory.DpProvider.GetDataList(dbModel.DbSelect);
            return ds;
        }

        /// <summary>
        /// 将字符串的网络参数替换
        /// </summary>
        /// <param name="str"></param>
        /// <param name="regex"></param>
        /// <returns></returns>
        public virtual string OperatPostParams(string str, Regex regex)
        {
            string name = regex.Match(str).Groups[1].Value;
            string text = HttpContext.Current.Request.Form[name];
            if (!string.IsNullOrEmpty(text))
            {
                return regex_text.Replace(str, text);
                //sb_searchwhere.Append(regex_text.Replace(item, text));
                //sb_searchwhere.Append(" and ");
            }
            return null;
        }

        public virtual string OperatPostParams(string str)
        {
            return OperatPostParams(str, regex_text);
        }

        /// <summary>
        /// 搜索条件处理
        /// </summary>
        /// <param name="dbModel"></param>
        protected virtual string GetSearchValue(DataPagingDb dbModel)
        {
            if (!string.IsNullOrEmpty(dbModel.DbOperat.SearchList))
            {
                System.Text.StringBuilder sb_searchwhere = new StringBuilder();
                foreach (string item in dbModel.DbOperat.SearchListItem)
                {
                    string value = item;
                    bool isSearch = true;
                    MatchCollection matchs = regex_text.Matches(value);
                    for (int i = 0; i < matchs.Count; i++)
                    {
                        Match match = matchs[i];
                        string name = match.Groups[1].Value;
                        string text;
                        if (this.IsSearchTypePost)
                        {
                            text = HttpContext.Current.Request.Form[name];
                        }
                        else
                        {
                            text = HttpContext.Current.Request.QueryString[name];
                        }
                        if (string.IsNullOrEmpty(text))
                        {
                            isSearch = false;
                            break;
                        }
//                        else
//                        {
//                            isSearch = true;
//                        }
                        value = regex_text.Replace(value, text, 1);
                    }
                    if (isSearch)
                    {
                        sb_searchwhere.Append(value);
                        sb_searchwhere.Append(" and ");
                    }

//                    string name = regex_text.Match(item).Groups[1].Value;
//                    string text;
//                    if (this.IsSearchTypePost)
//                    {
//                        text = HttpContext.Current.Request.Form[name];
//                    }
//                    else
//                    {
//                        text = HttpContext.Current.Request.QueryString[name];
//                    }
//                    if (!string.IsNullOrEmpty(text))
//                    {
//                        sb_searchwhere.Append(regex_text.Replace(item, text));
//                        sb_searchwhere.Append(" and ");
//                    }
                }
                if (sb_searchwhere.Length > 0)
                {
                    sb_searchwhere.Remove(sb_searchwhere.Length - 4, 4);
                    return sb_searchwhere.ToString();
                    //dbModel.DbSelect.StrWhere = dbModel.DbSelect.StrWhere + " and " + sb_searchwhere.ToString();
                }

            }
            return null;
        }
        /// <summary>
        /// 搜索的时候用post传递
        /// </summary>
        public bool IsSearchTypePost = true;


        /// <summary>
        /// 生成翻页的html
        /// </summary>
        /// <param name="dbModel"></param>
        /// <returns></returns>
        protected virtual string GetFanyeHtmlIfHas(DataPagingDb dbModel)
        {
            if (dbModel.HtmlFanye.IsHasFanye)
            {
                return this.GetFanyeHtml(dbModel);
            }
            else
            {
                return null;
            }
        }

        protected virtual string GetFanyeHtml(DataPagingDb dbModel)
        {
            if (string.IsNullOrEmpty(dbModel.HtmlFanye.FanyeHtml))
            {
                return null;
            }
            if (dbModel.DbSelect.ResultPages == 0)
            {
                dbModel.DbSelect.PageIndex = 0;
            }
            else if (dbModel.DbSelect.PageIndex >= dbModel.DbSelect.ResultPages)
            {
                dbModel.DbSelect.PageIndex = dbModel.DbSelect.ResultPages;
            }
            else if (dbModel.DbSelect.PageIndex < 1)
            {
                dbModel.DbSelect.PageIndex = 1;
            }
            //bool s = dbModel.AttrHtmlFanye.FanyeHtml.Contains("{{ResultCount}}");
            return dbModel.HtmlFanye.FanyeHtml.Replace(@"{{ResultCount}}", dbModel.DbSelect.ResultCount.ToString()).Replace("{{ResultPages}}", dbModel.DbSelect.ResultPages.ToString()).Replace(@"{{PageIndex}}", dbModel.DbSelect.PageIndex.ToString());
        }


    }
}
